import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {HttpService} from '@kylin/http';
import * as _ from 'lodash';
import {FrontPageService} from '../front-page.service';
import {LayersPanelService} from '../layers-panel/layers-panel.service';
import {ConfigService} from '@kylin/config';

@Component({
    selector: 'kylin-data-import',
    templateUrl: './data-import.component.html',
    styleUrls: ['./data-import.component.less'],
    providers: []
})
export class DataImportComponent implements OnInit {
    selectedValue = null;
    validateForm: FormGroup;
    translator = {
        organization: '请选择机构名称',
        labelName: '请填写标签名称',
        layersName: '请输入专题图名称',
        files: '请选择本地数据文件'
    };
    fileList: UploadFile[] = [];
    submitLoading = false;
    isVisible = false;
    currentLayersId = null;

    constructor(
        private nzMessageService: NzMessageService,
        private fb: FormBuilder,
        private http: HttpService,
        private frontPageService: FrontPageService,
        private layersPanelService: LayersPanelService,
        private configService: ConfigService
    ) {
    }

    ngOnInit() {
        this.validateForm = this.fb.group({
            layersName: [null, [Validators.required]],
            files: [null, [Validators.required]],
        });

        this.frontPageService.reloadLayersObservable.subscribe((data) => {
            this.fetchLayersData(this.currentLayersId, data);
        });

        // todo 下面是开发期使用的
        if (this.configService.uploadMock) {
            this.test();
        }
    }


    showModal(): void {
        this.isVisible = true;
    }

    handleOk(): void {
        this.isVisible = false;
    }

    handleCancel(): void {
        this.isVisible = false;
    }

    test() {
        this.nzMessageService.success('导入成功');
        this.fetchLayersData('6fdcb8f724f24ef48496c622e0aa7b89');
        // this.fetchLayersData('41e7b8dcdc0a4d2bb231a79104588cd0');
        // this.fetchLayersData('924bc0fa5cfc4624a5e4db7543df90d5');
        // this.fetchLayersData('e5ad58a37d6542df8ebb070667e3fd6d');
        // this.fetchLayersData('972f21eae26d4ba79948eb3179a187b0');
        // this.fetchLayersData('52566f4438614ff68cc91d94f54b296b');
    }

    submitForm(): void {
        this.submitLoading = true;
        const hasError = this.checkForm(this.validateForm.controls);
        if (hasError) {
            this.submitLoading = false;
            return;
        }
        const body = new FormData();
        const data = this.validateForm.value;
        _.forIn(data, (value, key) => {
            if (key !== 'files') {
                body.append(key, value);
            }
        });

        _.map(this.fileList, (value: any) => {
            body.append('files', value);
        });

        this.http.post('/layersLayer/uploadingAndPublishAtlas', body)
            .then(res => {
                this.submitLoading = false;
                if (res.resp_code === '10000') {
                    this.nzMessageService.success('导入成功');
                    // 上传成功以后拿到layersId去获取图层相关信息
                    this.fetchLayersData(res.data.layersId);
                } else {
                    this.nzMessageService.error(res.resp_msg);
                }
            })
            .catch(err => {
                this.submitLoading = false;
                this.nzMessageService.error(err.error.resp_msg || '导入失败');
            })

    }

    fetchLayersData(layersId: string, options?: any) {
        this.http.get(`/layersLayer/layersInfo/${layersId}`)
            .then(res => {
                this.currentLayersId = layersId;
                const layersMap = {};
                res.data.layerList.map(i => {
                    layersMap[i.layerId] = i;
                });
                const data = {...res.data.layers, layersMap, options};
                this.frontPageService.$changeNewLayersObservable(data);
                this.resetForm();
                this.isVisible = false;
                this.layersPanelService.$changeTitleObservable(options ? options.panel : '图层面板');
            })
            .catch(err => {

            })
    }

    resetForm() {
        this.validateForm.reset();
        this.fileList = [];
    }

    private checkForm(controls): boolean {
        let hasError = false;
        _.forIn(controls, (value, key) => {
            if (value.errors) {
                this.nzMessageService.error(this.translator[key]);
                hasError = true;
            }
        });
        return hasError;
    }

    beforeUpload = (file: UploadFile): boolean => {
        this.fileList = this.fileList.concat(file);
        this.validateForm.get('files').setValue(this.fileList);
        return false;
    };
}
